package com.dckj.auto.controller;


import cn.hutool.setting.dialect.Props;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.dckj.auto.common.enums.AuthAttribute;
import com.dckj.auto.common.interceptor.AuthorityAnnotation;
import com.dckj.auto.common.utils.AuthCode;
import com.dckj.auto.common.utils.JsonUtils;
import com.dckj.auto.common.utils.ehcache.EHCacheUtils;
import com.dckj.auto.common.utils.file.ForFile;
import com.dckj.auto.entity.AuthMenu;
import com.dckj.auto.service.AuthMenuService;
import com.xiaoleilu.hutool.json.JSONArray;
import com.xiaoleilu.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author WangDong123
 * @since 2018-09-03
 */
@Controller
@RequestMapping("/auth/menu/")
public class AuthMenuController {

    Props prop = new Props("config.properties","UTF-8");
    private  String authTokenCacheKey = prop.getStr("auth_token_cache_key");

    @Autowired
    AuthMenuService menuService;

    @AuthorityAnnotation(authority = AuthCode.AUTH_MENU_PAGE)
    @RequestMapping(value = "page")
    public String page(HttpServletRequest request){
        //获取权限属性集合
        List<JSONObject> objectList = AuthAttribute.toJSONArray();
        request.setAttribute("attribute",objectList);
        return "auth-menu/list";
    }

    @RequestMapping(value = "list")
    @ResponseBody
    public JSONObject list(Integer attribute){
        List<AuthMenu> list = menuService.list(attribute);
        JSONArray objects = JSONUtil.parseArray(list);
        return JsonUtils.successTree(objects, list.size());
    }

    @AuthorityAnnotation(authority = AuthCode.CREATE_AUTH_MENU)
    @RequestMapping(value = "toInsert")
    public String toInsert(HttpServletRequest request,String menuId,Integer insert,Integer attribute){
        if(StringUtils.isNotEmpty(menuId)){
            String[] split = menuId.split(",");
            if(split.length>0){
                menuId = split[0];
            }
        }
        if(StringUtils.isNotEmpty(menuId) ){//不为空 要么是编辑 要么是新增菜单或按钮
            request.setAttribute("child",1);
            AuthMenu autoMenu = menuService.selectById(menuId);
            if(insert.equals(2)){//编辑
                request.setAttribute("menu",autoMenu);
            }else{//新增
                Map<String, Object> map = menuService.selectMap(new EntityWrapper<AuthMenu>().setSqlSelect(" max(num) as num ").eq("attribute",attribute));
                if(null == map ){
                    request.setAttribute("maxNum",0);
                    request.setAttribute("authorityId",0);
                }else{
                    request.setAttribute("maxNum",Integer.valueOf(map.get("num").toString())+1);
                    request.setAttribute("authorityId",Integer.valueOf(map.get("num").toString())+1);
                }
                request.setAttribute("fatherId",menuId);
                request.setAttribute("parentId",autoMenu.getAuthorityId());
            }
            request.setAttribute("attribute",autoMenu.getAttribute());
            if(autoMenu.getParentId().equals(-1) && insert.equals(2)){
                request.setAttribute("type",0);
            }else{
                request.setAttribute("type",1);
            }
        }else{//新增顶级目录
            request.setAttribute("type",0);
            request.setAttribute("maxNum",0);
            request.setAttribute("authorityId",0);
            request.setAttribute("parentId",-1);
            request.setAttribute("fatherId",0);
            //获取权限属性集合
            List<JSONObject> objectList = AuthAttribute.toJSONArray();
            List<Map<String, Object>> maps = menuService.selectMaps(new EntityWrapper<AuthMenu>().setSqlSelect("attribute").groupBy("attribute"));
            if(null == maps){
                request.setAttribute("attributes",objectList);
            }else{
                List<JSONObject> list = new ArrayList<>();
                List<Integer> haves = new ArrayList<>();
                for (Map<String, Object> map : maps){
                    Integer integer = (Integer) map.get("attribute");//已经添加过的
                    haves.add(integer);
                }
                for (JSONObject object : objectList){
                    Integer value = object.getInteger("value");
                    if(!haves.contains(value)){
                        list.add(object);
                    }
                }
                request.setAttribute("attributes",list);
            }
        }
        return "auth-menu/edit";
    }


    @AuthorityAnnotation(authority = AuthCode.CREATE_AUTH_MENU)
    @RequestMapping(value = "edit")
    @ResponseBody
    public JSONObject edit(AuthMenu autoMenu, boolean open){
        String msg = StringUtils.isEmpty(autoMenu.getMenuId())?"新增":"编辑";
        Integer insert = menuService.saveOrUpdate(autoMenu);
        List<AuthMenu> autoMenus = menuService.selectList(new EntityWrapper<AuthMenu>().and("code!={0}", "").groupBy("code").orderBy("num"));
        ForFile.createFile(autoMenus,open);
        if(insert>0){
            EHCacheUtils cache = EHCacheUtils.getInstance();
            cache.remove(authTokenCacheKey);//清除用户权限缓存
            return JsonUtils.success(msg+"菜单数据");
        }
        return JsonUtils.error(true,msg+"菜单数据");
    }


    @AuthorityAnnotation(authority = AuthCode.DELETE_AUTH_MENU)
    @RequestMapping(value = "delete")
    @ResponseBody
    public JSONObject delete(String menuId){
        Integer delete = menuService.delete(menuId);
        String msg = "删除";
        if(delete>0){
            EHCacheUtils cache = EHCacheUtils.getInstance();
            cache.remove(authTokenCacheKey);//清除用户权限缓存
            return JsonUtils.success(msg+"菜单数据");
        }
        return JsonUtils.error(true,msg+"菜单数据");
    }


    @ResponseBody
    @RequestMapping(value = "checkCode")
    public JSONObject checkCode(String code){
        JSONObject jsonObject = new JSONObject();
        AuthMenu menu = menuService.selectOne(new EntityWrapper<AuthMenu>().like("code", code));
        if(menu != null){//存在
            jsonObject.put("menuId",menu.getMenuId());
            return JsonUtils.success(jsonObject);
        }
        return JsonUtils.error(false,"");//没有直接返回
    }
}

